//批量加载模型文件
import { EventDispatcher, Loader } from "three";
import { gltfLoader } from "./LoaderConfig";
export default class LoaderManager extends EventDispatcher {
  total: number = 0;
  success: number = 0;
  error: number = 0;
  loaderMap: { [key: string]: Loader } = {
    gltf: gltfLoader,
  };
  sourceMap: { [key: string]: any } = {};
  constructor() {
    super();
  }
  load(urls: string[], basePath = "./model/"):this {
    this.total = urls.length;
    for (const url of urls) {
      const ext = url.split(".").pop();
      if (ext && this.loaderMap[ext]) {
        if (this.sourceMap[url]) {
          this.success += 1;
          this.dispatchLoaded();
          continue;
        }
        const loader = this.loaderMap[ext];
        loader
          .loadAsync(basePath + url)
          .then((res) => {
            this.sourceMap[url] = res;
            this.success += 1;
            this.dispatchLoaded();
          })
          .catch((err) => {
            new Error(`${err}：${url}`);
            this.error += 1;
            this.dispatchLoaded();
          });
      } else {
        this.error += 1;
        new Error(`找不到对应loader：${url}`);
        continue;
      }
    }
    return this
  }
  private dispatchLoaded() {
    this.dispatchEvent({
      type: "loading",
      data: {
        total: this.total,
        success: this.success,
        error: this.error,
      },
    });
    if (this.total === this.success + this.error) {
      this.dispatchEvent({
        type: "loaded",
        data: this.sourceMap,
      });
    }
  }
}
export const DefaultLoaderanager = new LoaderManager();
